package cn.highset.common.utils;

import cn.highset.common.constant.SettingConstant;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Victor
 */
@Slf4j
public class CommonUtil {
    private static String dx = "零一二三四五六七八九十";

    /**
     * 以UUID重命名
     *
     * @param fileName
     * @return
     */
    public static String renamePic(String fileName) {
        String extName = fileName.substring(fileName.lastIndexOf("."));
        return UUID.randomUUID().toString().replace("-", "") + extName;
    }

    /**
     * 小写数字 转大写数字
     *
     * @param number
     * @return
     */
    public static String smallNumberTobig(String number) {
        if (number == null || number.trim().length() == 0) {
            return "";
        }
        number = number.trim();
        for (int i = 0; i < number.length(); i++) {
            String a = String.valueOf(number.charAt(i));
            int b = Integer.parseInt(a);
            String d1 = String.valueOf(dx.charAt(b));
            number = number.replaceFirst(a, d1);

        }
        return number;
    }


    /**
     * 发送https请求
     *
     * @param requestUrl    请求地址
     * @param requestMethod 请求方式（GET、POST）
     * @param outputStr     提交的数据
     * @return JSONObject(通过JSONObject.get ( key)的方式获取json对象的属性值)
     */
    public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            conn.setRequestMethod(requestMethod);

            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamRead_er = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedRead_er = new BufferedReader(inputStreamRead_er);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedRead_er.readLine()) != null) {
                buffer.append(str);
            }

            // 释放资源
            bufferedRead_er.close();
            inputStreamRead_er.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (ConnectException ce) {
            log.error("连接超时：{}", ce);
        } catch (Exception e) {
            log.error("https请求异常：{}", e);
        }
        return jsonObject;
    }

    /**
     * 生成订单的编号ord_er_sn
     */
    public static String generateOrd_erNumber() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        String timeStr = DateUtils.format(cal.getTime(), DateUtils.DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS_SSS);
        return timeStr + CharUtil.getRandomNum(6);
    }

    public static String getSha1(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            // TODO: handle exception
            return null;
        }
    }

    /**
     * @param ts 开始日期
     * @param te 结束日期
     * @return
     */
    public static String getShowDate(Date ts, Date te, Boolean showTime) {
        if (showTime == null) {
            showTime = false;
        }
        int y_s = DateUtil.year(ts);//开始年份
        int m_s = DateUtil.month(ts) + 1;//开始月份
        int d_s = DateUtil.dayOfMonth(ts);//月里面的天
        String HHmm_s = DateUtil.format(ts, "HH:mm");
        // int hour_s = DateUtil.hour(ts,true);//开始小时
        // int minute_s = DateUtil.minute(ts);//开始分钟
        // int second_s = DateUtil.second(ts);//开始秒


        int y_e = DateUtil.year(te);//结束年份
        int m_e = DateUtil.month(te) + 1;//结束月份
        int d_e = DateUtil.dayOfMonth(te);//月里面的天
        String HHmm_e = DateUtil.format(te, "HH:mm");
        // int hour_e = DateUtil.hour(ts,true);//结束小时
        // int minute_e = DateUtil.minute(ts);//结束分钟
        // int second_e = DateUtil.second(ts);//结束秒


        if (y_s == y_e) {//如果开始年份 等于结束年份
            if (m_s == m_e) {//如果月份相同
                if (d_s == d_e) {//如果天数相同
                    return showTime ? String.format("%d年%d月%d日 %s-%s", y_s, m_s, d_s, HHmm_s, HHmm_e) : String.format("%d年%d月%d日", y_s, m_s, d_s);
                } else {
                    return showTime ? String.format("%d年%d月%d日 %s-%d日 %s", y_s, m_s, d_s, HHmm_s, d_e, HHmm_e) : String.format("%d年%d月%d日-%d日", y_s, m_s, d_s, d_e);
                }
            } else {
                return showTime ? String.format("%d年%d月%d日 %s-%d月%d日  %s", y_s, m_s, d_s, HHmm_s, m_e, d_e, HHmm_e) : String.format("%d年%d月%d日-%d月%d日", y_s, m_s, d_s, m_e, d_e);
            }
        } else {
            return showTime ? String.format("%d年%d月%d日 %s-%d年%d月%d日 %s", y_s, m_s, d_s, HHmm_s, y_e, m_e, d_e, HHmm_e) : String.format("%d年%d月%d日-%d年%d月%d日", y_s, m_s, d_s, y_e, m_e, d_e);
        }
    }

    /**
     * @param ts 开始日期
     * @param te 结束日期
     * @return
     */
    public static String getShowDateEn(Date ts, Date te, Boolean showTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("MMM", Locale.UK);
        int y_s = DateUtil.year(ts);//开始年份
        int m_s = DateUtil.month(ts) + 1;//开始月份
        String month_s = sdf.format(ts);
        String HHmm_s = DateUtil.format(ts, "HH:mm");

        int d_s = DateUtil.dayOfMonth(ts);//月里面的天
        int y_e = DateUtil.year(te);//开始年份
        int m_e = DateUtil.month(te) + 1;//开始月份
        String month_e = sdf.format(te);
        int d_e = DateUtil.dayOfMonth(te);//月里面的天
        String HHmm_e = DateUtil.format(te, "HH:mm");

        if (y_s == y_e) {//如果开始年份 等于结束年份
            if (m_s == m_e) {//如果月份相同
                if (d_s == d_e) {//如果天数相同
                    return showTime ? String.format("%s.%d.%d %s-%s", month_s, d_s, y_s, HHmm_s, HHmm_e) : String.format("%s.%d.%d", month_s, d_s, y_s);//月日年
                } else {
                    return showTime ? String.format("%s.%d %s-%s.%d.%d %s", month_s, d_s, HHmm_s, month_e, d_e, y_e, HHmm_e) : String.format("%s.%d-%s.%d.%d", month_s, d_s, month_e, d_e, y_e);
                }
            } else {
                return showTime ? String.format("%s.%d %s-%s.%d.%d %s", month_s, d_s, HHmm_s, month_e, d_e, y_e, HHmm_e) : String.format("%s.%d-%s.%d.%d", month_s, d_s, month_e, d_e, y_e);
            }
        } else {
            return showTime ? String.format("%s.%d.%d %s-%s.%d.%d %s", month_s, d_s, y_s, HHmm_s, month_e, d_e, y_e, HHmm_e) : String.format("%s.%d.%d-%s.%d.%d", month_s, d_s, y_s, month_e, d_e, y_e);
        }
    }

    public static void main(String[] args) throws ParseException {
        // Date ts  = new SimpleDateFormat("yyyyMMdd").parse("20180925");
        // Date te  = new SimpleDateFormat("yyyyMMdd").parse("20190925");
        //System.out.println(getShowDateEn(ts,te));

        //Date d  = new SimpleDateFormat("yyyyMMdd").parse("20190925");
        //System.out.println( new SimpleDateFormat("MMM", Locale.UK).format(d));
    }

    /**
     * 获得短信模版Key
     *
     * @param type
     * @return
     */
    public static String getSmsTemplate(Integer type) {
        switch (type) {
            case 0:
                return SettingConstant.ALI_SMS_COMMON;
            case 1:
                return SettingConstant.ALI_SMS_REGIST;
            case 2:
                return SettingConstant.ALI_SMS_LOGIN;
            case 3:
                return SettingConstant.ALI_SMS_CHANGE_MOBILE;
            case 4:
                return SettingConstant.ALI_SMS_CHANG_PASS;
            case 5:
                return SettingConstant.ALI_SMS_RESET_PASS;
            case 6:
                return SettingConstant.ALI_SMS_ACTIVITI;
            default:
                return SettingConstant.ALI_SMS_COMMON;
        }
    }

    /**
     * 随机6位数生成
     */
    public static String getRandomNum() {

        Random random = new Random();
        int num = random.nextInt(999999);
        //不足六位前面补0
        String str = String.format("%06d", num);
        return str;
    }
}
